const { dialog } = require('@electron/remote');
const { ipcRenderer } = require('electron');
const simpleGit = require('simple-git');
const path = require('path');
const fs = require('fs');

interface DefaultLogFields {
    hash: string;
    date: string;
    message: string;
    refs: string;
    body: string;
    author_name: string;
}

interface CommitDetail extends DefaultLogFields {
    diff?: string;
    files?: string[];
}

interface GitChange {
    commits: CommitDetail[];
    modified: string[];
    created: string[];
    deleted: string[];
    diffs: { [key: string]: string };
}

interface Project {
    path: string;
    name: string;
    description: string;
}

class ProjectManager {
    private projects: Project[] = [];
    private projectListElement: HTMLElement;
    private startDateInput: HTMLInputElement;
    private endDateInput: HTMLInputElement;
    private projectModal: HTMLElement;
    private projectNameInput: HTMLInputElement;
    private projectDescriptionInput: HTMLTextAreaElement;
    private selectedPath: string = '';

    constructor() {
        this.projectListElement = document.getElementById('projectList')!;
        this.startDateInput = document.getElementById('startDate') as HTMLInputElement;
        this.endDateInput = document.getElementById('endDate') as HTMLInputElement;
        this.projectModal = document.getElementById('projectModal') as HTMLElement;
        this.projectNameInput = document.getElementById('projectName') as HTMLInputElement;
        this.projectDescriptionInput = document.getElementById('projectDescription') as HTMLTextAreaElement;
        
        // 设置默认日期为今天
        const today = new Date();
        const todayStr = this.formatDate(today);
        this.startDateInput.value = todayStr;
        this.endDateInput.value = todayStr;

        this.initializeEventListeners();
        this.loadProjects(); // 加载保存的项目
    }

    // 加载保存的项目
    private async loadProjects() {
        const savedProjects = await ipcRenderer.invoke('get-config', 'projects');
        if (savedProjects) {
            this.projects = savedProjects;
            this.renderProjects();
        }
    }

    // 保存项目到配置
    private async saveProjects() {
        await ipcRenderer.invoke('set-config', 'projects', this.projects);
    }

    private formatDate(date: Date): string {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    private initializeEventListeners() {
        const addProjectButton = document.getElementById('addProject');
        const generateReportButton = document.getElementById('generateReport');
        const confirmProjectButton = document.getElementById('confirmProject');
        const cancelProjectButton = document.getElementById('cancelProject');

        if (addProjectButton) {
            addProjectButton.addEventListener('click', () => this.showProjectDialog());
        }

        if (generateReportButton) {
            generateReportButton.addEventListener('click', () => this.generateReport());
        }

        if (confirmProjectButton) {
            confirmProjectButton.addEventListener('click', () => this.confirmAddProject());
        }

        if (cancelProjectButton) {
            cancelProjectButton.addEventListener('click', () => this.hideProjectDialog());
        }
    }

    private async showProjectDialog() {
        const result = await dialog.showOpenDialog({
            properties: ['openDirectory']
        });

        if (!result.canceled && result.filePaths.length > 0) {
            this.selectedPath = result.filePaths[0];
            const defaultName = this.selectedPath.split('\\').pop() || this.selectedPath.split('/').pop() || this.selectedPath;
            
            // 设置默认项目名称
            this.projectNameInput.value = defaultName;
            this.projectDescriptionInput.value = '';
            
            // 显示对话框
            this.projectModal.style.display = 'block';
        }
    }

    private hideProjectDialog() {
        this.projectModal.style.display = 'none';
        this.selectedPath = '';
        this.projectNameInput.value = '';
        this.projectDescriptionInput.value = '';
    }

    private confirmAddProject() {
        if (!this.selectedPath || !this.projectNameInput.value.trim()) {
            return;
        }

        this.projects.push({
            path: this.selectedPath,
            name: this.projectNameInput.value.trim(),
            description: this.projectDescriptionInput.value.trim()
        });

        this.saveProjects(); // 保存项目配置
        this.hideProjectDialog();
        this.renderProjects();
    }

    private renderProjects() {
        this.projectListElement.innerHTML = '';
        
        this.projects.forEach((project, index) => {
            const projectElement = document.createElement('div');
            projectElement.className = 'project-item';

            // 创建项目信息显示元素
            const infoElement = document.createElement('div');
            infoElement.className = 'project-path';
            infoElement.innerHTML = `
                <strong>${project.name}</strong>
                ${project.description ? `<br><small>${project.description}</small>` : ''}
                <br><small class="path">${project.path}</small>
            `;
            projectElement.appendChild(infoElement);

            // 创建删除按钮
            const deleteButton = document.createElement('button');
            deleteButton.className = 'delete-btn';
            deleteButton.textContent = '删除';
            deleteButton.onclick = () => this.deleteProject(index);
            projectElement.appendChild(deleteButton);

            this.projectListElement.appendChild(projectElement);
        });
    }

    private deleteProject(index: number) {
        this.projects.splice(index, 1);
        this.saveProjects(); // 保存项目配置
        this.renderProjects();
    }

    private async getGitChanges(projectPath: string): Promise<GitChange> {
        const git = simpleGit(projectPath);
        
        try {
            // 获取指定日期范围的提交记录
            const startDate = new Date(this.startDateInput.value);
            const endDate = new Date(this.endDateInput.value);
            // 将结束日期设置为当天的最后一秒
            endDate.setHours(23, 59, 59, 999);

            const logs = await git.log([
                `--since="${this.formatDate(startDate)} 00:00:00"`,
                `--until="${this.formatDate(endDate)} 23:59:59"`
            ]);

            // 获取每个提交的详细信息
            const commitsWithDetails = await Promise.all(
                logs.all.map(async (commit: DefaultLogFields) => {
                    // 获取此次提交的文件列表
                    const fileList = await git.raw([
                        'diff-tree',
                        '--no-commit-id',
                        '--name-only',
                        '-r',
                        commit.hash
                    ]);

                    // 获取此次提交的具体改动
                    const diff = await git.raw([
                        'show',
                        commit.hash,
                        '--patch',
                        '--stat'
                    ]);

                    return {
                        ...commit,
                        files: fileList.split('\n').filter((f: string) => f.trim()),
                        diff: diff
                    };
                })
            );

            // 获取当前未提交的更改
            const status = await git.status();
            
            // 获取文件差异
            const diffs: { [key: string]: string } = {};
            
            // 获取已修改文件的差异
            for (const file of status.modified) {
                const diff = await git.diff(['HEAD', '--', file]);
                diffs[file] = diff;
            }
            
            // 获取新建文件的内容
            for (const file of status.created) {
                try {
                    const fileContent = await git.raw(['show', `:${file}`]);
                    diffs[file] = fileContent;
                } catch (error) {
                    // 如果文件未暂存，直接读取文件内容
                    const fullPath = path.join(projectPath, file);
                    if (fs.existsSync(fullPath)) {
                        diffs[file] = fs.readFileSync(fullPath, 'utf-8');
                    } else {
                        diffs[file] = '文件内容无法读取';
                    }
                }
            }

            return {
                commits: commitsWithDetails,
                modified: status.modified,
                created: status.created,
                deleted: status.deleted,
                diffs
            };
        } catch (error) {
            console.error('获取Git变更失败:', error);
            return {
                commits: [],
                modified: [],
                created: [],
                deleted: [],
                diffs: {}
            };
        }
    }

    private formatChangesForAI(changes: GitChange): string {
        let report = '项目变更记录：\n\n';

        // 添加提交记录
        if (changes.commits.length > 0) {
            report += '## 提交记录\n\n';
            changes.commits.forEach(commit => {
                report += `### ${commit.date} - ${commit.message}\n`;
                report += `作者: ${commit.author_name}\n`;
                if (commit.body) {
                    report += `描述: ${commit.body}\n`;
                }
                if (commit.files && commit.files.length > 0) {
                    report += '\n变更的文件:\n';
                    commit.files.forEach(file => {
                        report += `- ${file}\n`;
                    });
                }
                if (commit.diff) {
                    report += '\n具体改动:\n```diff\n' + commit.diff + '\n```\n';
                }
                report += '\n---\n\n';
            });
        }

        // 添加未提交的变更
        if (changes.modified.length > 0 || changes.created.length > 0 || changes.deleted.length > 0) {
            report += '## 未提交的变更\n';
            
            if (changes.modified.length > 0) {
                report += '\n### 修改的文件：\n';
                changes.modified.forEach(file => {
                    report += `- ${file}\n\`\`\`diff\n${changes.diffs[file]}\n\`\`\`\n`;
                });
            }

            if (changes.created.length > 0) {
                report += '\n### 新建的文件：\n';
                changes.created.forEach(file => {
                    report += `- ${file}\n\`\`\`\n${changes.diffs[file]}\n\`\`\`\n`;
                });
            }

            if (changes.deleted.length > 0) {
                report += '\n### 删除的文件：\n';
                changes.deleted.forEach(file => {
                    report += `- ${file}\n`;
                });
            }
        }

        return report;
    }

    private async generateReport() {
        let allChanges = '';
        
        for (const project of this.projects) {
            const changes = await this.getGitChanges(project.path);
            const formattedChanges = this.formatChangesForAI(changes);
            allChanges += `\n# ${project.name}\n${formattedChanges}\n`;
        }

        console.log('生成的变更报告:', allChanges);
        // TODO: 后续将发送给 ChatGPT
    }
}

// 初始化项目管理器
new ProjectManager(); 